<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>聊呗</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            margin: 0;
            padding: 20px;
            background: #1a1a1a;
            overflow: hidden;
        }

        /* 登录后的界面使用原有背景 */
        body.logged-in {
            background-image: url('/static/flowers.jpg');
            background-size: cover;
            background-position: center;
            background-repeat: no-repeat;
            background-attachment: fixed;
            overflow: auto;
        }

        /* 心形样式 */
        .heart {
            position: absolute;
            width: 20px;
            height: 20px;
            background: #ff69b4;
            transform: rotate(45deg);
            animation: fall linear infinite;
            z-index: 1;
        }

        /* 登录后隐藏动画元素 */
        body.logged-in .heart,
        body.logged-in .firework,
        body.logged-in .particle {
            display: none;
        }

        .heart:before,
        .heart:after {
            content: '';
            width: 20px;
            height: 20px;
            background: inherit;
            border-radius: 50%;
            position: absolute;
        }

        .heart:before {
            left: -10px;
        }

        .heart:after {
            top: -10px;
        }

        @keyframes fall {
            0% {
                transform: rotate(45deg) translateX(0) translateY(-100vh);
                opacity: 1;
            }
            100% {
                transform: rotate(45deg) translateX(100px) translateY(100vh);
                opacity: 0;
            }
        }

        /* 烟花样式 */
        .firework {
            position: absolute;
            width: 4px;
            height: 4px;
            border-radius: 50%;
            animation: explode 1.2s ease-out forwards;
            box-shadow: 0 0 10px 2px rgba(255, 255, 255, 0.3);
            z-index: 1;
        }

        @keyframes explode {
            0% {
                transform: scale(1);
                opacity: 1;
            }
            100% {
                transform: scale(40);
                opacity: 0;
            }
        }

        .particle {
            position: absolute;
            width: 3px;
            height: 3px;
            border-radius: 50%;
            animation: shoot 1.2s ease-out forwards;
            box-shadow: 0 0 6px 1px rgba(255, 255, 255, 0.3);
            z-index: 1;
        }

        @keyframes shoot {
            0% {
                transform: translateX(0) translateY(0);
                opacity: 1;
            }
            100% {
                transform: translateX(var(--tx)) translateY(var(--ty));
                opacity: 0;
            }
        }

        #authForm, #registerForm {
            background: rgba(255, 255, 255, 0.9);
            padding: 30px;
            border-radius: 15px;
            box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
            position: relative;
            z-index: 2;
            backdrop-filter: blur(10px);
            max-width: 400px;
            margin: 50px auto;
        }
        .container {
            max-width: 800px;
            margin: 0 auto;
        }
        #authForm, #loginForm, #chatRoom {
            background: white;
            padding: 20px;
            border-radius: 8px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
            margin-bottom: 20px;
        }
        #loginForm, #chatRoom, #registerForm {
            display: none;
        }
        #messages {
            height: 400px;
            overflow-y: auto;
            border: 1px solid rgba(221, 221, 221, 0.5);
            padding: 10px;
            margin-bottom: 10px;
            border-radius: 4px;
            background: rgba(255, 255, 255, 0.4);
        }
        .message {
            margin-bottom: 10px;
            padding: 8px 12px;
            border-radius: 15px;
            max-width: 70%;
            word-wrap: break-word;
        }
        .message-left {
            background: rgba(233, 236, 239, 0.6);
            float: left;
            clear: both;
            border-bottom-left-radius: 5px;
            backdrop-filter: blur(5px);
        }
        .message-right {
            background: rgba(0, 123, 255, 0.6);
            color: white;
            float: right;
            clear: both;
            border-bottom-right-radius: 5px;
            backdrop-filter: blur(5px);
        }
        .system-message {
            color: #666;
            font-style: italic;
            text-align: center;
            clear: both;
            float: none;
            background: none;
            margin: 10px auto;
            max-width: 100%;
            opacity: 1;
            transition: opacity 0.5s ease-in-out;
        }
        .system-message.fade-out {
            opacity: 0;
        }
        input[type="text"], input[type="password"], input[type="submit"] {
            padding: 8px;
            margin: 5px;
            border: 1px solid #ddd;
            border-radius: 4px;
            width: calc(100% - 26px);
        }
        input[type="submit"] {
            background: #007bff;
            color: white;
            border: none;
            cursor: pointer;
            width: 100%;
        }
        input[type="submit"]:hover {
            background: #0056b3;
        }
        #messageForm {
            display: flex;
            gap: 10px;
        }
        #messageInput {
            flex-grow: 1;
            width: auto;
        }
        .form-group {
            margin-bottom: 15px;
        }
        .switch-form {
            text-align: center;
            margin-top: 10px;
        }
        .switch-form a {
            color: #007bff;
            text-decoration: none;
            cursor: pointer;
        }
        .switch-form a:hover {
            text-decoration: underline;
        }
        .error-message {
            color: #dc3545;
            margin-top: 5px;
            font-size: 14px;
        }
        #sendButton, #leaveButton {
            width: auto;
        }
        #loginForm {
            background: white;
            padding: 20px;
            border-radius: 8px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
            margin-bottom: 20px;
        }
        .room-list {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
            gap: 15px;
            margin-top: 20px;
        }
        .room-card {
            background: white;
            padding: 15px;
            border-radius: 8px;
            box-shadow: 0 1px 3px rgba(0,0,0,0.1);
            cursor: pointer;
            transition: transform 0.2s;
        }
        .room-card:hover {
            transform: translateY(-2px);
            box-shadow: 0 2px 5px rgba(0,0,0,0.15);
        }
        .room-name {
            font-size: 18px;
            font-weight: bold;
            color: #1a73e8;
            margin-bottom: 5px;
        }
        .room-info {
            font-size: 14px;
            color: #666;
            margin-bottom: 3px;
        }
        .room-description {
            font-size: 14px;
            color: #444;
            margin-top: 8px;
        }
        #messages::after {
            content: '';
            display: table;
            clear: both;
        }
        .message-container {
            margin-bottom: 15px;
            overflow: hidden;
            display: flex;
            align-items: flex-start;
            gap: 10px;
        }
        
        .message-container.right {
            flex-direction: row-reverse;
        }

        .message-avatar {
            width: 40px;
            height: 40px;
            border-radius: 50%;
            background: #1aad19;
            color: white;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 16px;
            flex-shrink: 0;
            background-size: cover;
            background-position: center;
            background-repeat: no-repeat;
        }

        .message-avatar.tiger {
            background: #ff9800;
            color: #fff;
            font-size: 20px;
        }

        .message-avatar.fish {
            background: transparent;
            color: transparent;
            font-size: 20px;
        }

        .message-content-wrapper {
            display: flex;
            flex-direction: column;
            max-width: calc(70% - 50px);
        }

        .message {
            margin-bottom: 0;
            padding: 8px 12px;
            border-radius: 15px;
            word-wrap: break-word;
            width: fit-content;
        }
        .message-sender {
            font-size: 12px;
            color: #666;
            margin-bottom: 2px;
            margin-left: 12px;
        }
        .message-sender-right {
            text-align: right;
            margin-right: 12px;
        }
        #chatRoom {
            display: none;
            background: transparent;
            padding: 20px;
            border-radius: 8px;
            margin-bottom: 20px;
        }
        .chat-container {
            display: flex;
            height: 80vh;
            margin: 0;
            padding: 0;
            background: transparent;
            border-radius: 8px;
        }
        .chat-main {
            flex: 1;
            display: flex;
            flex-direction: column;
            border-right: none;
            background: transparent;
        }
        #messages {
            flex: 1;
            overflow-y: auto;
            padding: 20px;
            background: transparent;
            border: none;
        }
        .chat-header {
            padding: 15px 20px;
            background: rgba(255, 255, 255, 0.2);
            border-bottom: 1px solid rgba(255, 255, 255, 0.1);
            display: flex;
            justify-content: space-between;
            align-items: center;
            height: 40px;
            backdrop-filter: blur(5px);
        }
        .chat-header h2 {
            margin: 0;
            font-size: 16px;
            color: #333;
        }
        #messageForm {
            padding: 15px 20px;
            background: rgba(255, 255, 255, 0.2);
            border-top: 1px solid rgba(255, 255, 255, 0.1);
            display: flex;
            gap: 10px;
            height: 50px;
            backdrop-filter: blur(5px);
        }
        .chat-sidebar {
            width: 250px;
            background: rgba(255, 255, 255, 0.2);
            display: flex;
            flex-direction: column;
            border-left: 1px solid rgba(255, 255, 255, 0.1);
            backdrop-filter: blur(5px);
        }
        .user-info {
            padding: 15px;
            background: #f6f6f6;
            border-bottom: 1px solid #e0e0e0;
        }
        .online-users {
            flex: 1;
            overflow-y: auto;
        }
        .online-users-title {
            padding: 10px 15px;
            font-size: 14px;
            color: #333;
            background: rgba(255, 255, 255, 0.2);
            border-bottom: 1px solid rgba(255, 255, 255, 0.1);
            backdrop-filter: blur(5px);
        }
        .user-list {
            padding: 10px 0;
        }
        .user-item {
            padding: 8px 15px;
            display: flex;
            align-items: center;
            cursor: pointer;
        }
        .user-item:hover {
            background: rgba(233, 233, 233, 0.4);
        }
        .user-item-avatar {
            width: 40px;
            height: 40px;
            border-radius: 50%;
            background: #1aad19;
            color: white;
            display: flex;
            align-items: center;
            justify-content: center;
            margin-right: 10px;
            font-size: 16px;
            background-size: cover;
            background-position: center;
            background-repeat: no-repeat;
        }
        .user-item-avatar.tiger {
            background: #ff9800;
            color: #fff;
            font-size: 20px;
        }
        .user-item-avatar.fish {
            background: transparent;
            color: transparent;
            font-size: 20px;
        }
        .user-item-name {
            color: #333;
            font-size: 14px;
        }
        #messageInput {
            flex: 1;
            border: 1px solid #e0e0e0;
            border-radius: 4px;
            padding: 8px 12px;
            font-size: 14px;
        }
        #sendButton, #leaveButton {
            padding: 8px 20px;
            background: #1aad19;
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
        }
        #leaveButton {
            background: #ff4d4f;
        }
        .message-left {
            background: rgba(233, 236, 239, 0.4);
            float: left;
            clear: both;
            border-bottom-left-radius: 5px;
            backdrop-filter: blur(5px);
        }
        .message-right {
            background: rgba(0, 123, 255, 0.4);
            color: white;
            float: right;
            clear: both;
            border-bottom-right-radius: 5px;
            backdrop-filter: blur(5px);
        }
        .gender-group {
            margin-bottom: 15px;
        }
        .avatar-group {
            margin-bottom: 15px;
        }
        .avatar-label {
            display: block;
            margin-bottom: 8px;
            color: #333;
            font-weight: bold;
        }
        .avatar-options {
            display: flex;
            gap: 10px;
            flex-wrap: wrap;
        }
        .avatar-option {
            width: 50px;
            height: 50px;
            border-radius: 50%;
            cursor: pointer;
            border: 2px solid transparent;
            padding: 2px;
        }
        .avatar-option:hover {
            border-color: #007bff;
        }
        .avatar-option.selected {
            border-color: #28a745;
        }
        .avatar-option img {
            width: 100%;
            height: 100%;
            border-radius: 50%;
            object-fit: cover;
        }
        .gender-label {
            display: block;
            margin-bottom: 8px;
            color: #333;
            font-weight: bold;
        }
        .gender-select {
            width: 100%;
            padding: 10px;
            border: 2px solid #ddd;
            border-radius: 4px;
            font-size: 14px;
            background-color: white;
            cursor: pointer;
            transition: border-color 0.3s;
        }
        .gender-select:hover {
            border-color: #007bff;
        }
        .gender-select:focus {
            outline: none;
            border-color: #007bff;
            box-shadow: 0 0 0 2px rgba(0,123,255,0.25);
        }
        .required-field {
            color: #dc3545;
            margin-left: 4px;
        }
        .field-tip {
            font-size: 12px;
            color: #666;
            margin-top: 4px;
            margin-bottom: 8px;
        }
    </style>
</head>
<body>
    <div class="container">
        <div id="authForm">
            <h2>欢迎L O G I N</h2>
            <div class="form-group">
                <input type="text" id="loginUsername" placeholder="用户名" required>
            </div>
            <div class="form-group">
                <input type="password" id="loginPassword" placeholder="密码" required>
            </div>
            <div class="form-group">
                <input type="submit" value="现在登录" onclick="login()">
            </div>
            <div class="switch-form">
                你还没有账号？<a onclick="showRegisterForm()">原地注册</a>
            </div>
            <div id="loginError" class="error-message"></div>
        </div>

        <div id="registerForm">
            <h2>用户注册</h2>
            <div class="form-group">
                <label class="input-label">用户名<span class="required-field">*</span></label>
                <input type="text" id="registerUsername" placeholder="请输入用户名" required>
                <div class="field-tip">用户名将显示在聊天室中</div>
            </div>
            <div class="form-group">
                <label class="input-label">密码<span class="required-field">*</span></label>
                <input type="password" id="registerPassword" placeholder="请输入密码" required>
            </div>
            <div class="form-group">
                <label class="input-label">确认密码<span class="required-field">*</span></label>
                <input type="password" id="confirmPassword" placeholder="请再次输入密码" required>
            </div>
            <div class="avatar-group">
                <label class="avatar-label">选择头像<span class="required-field">*</span></label>
                <div class="avatar-options">
                    <div class="avatar-option" data-avatar="default">
                        <div style="width: 100%; height: 100%; background: #1aad19; border-radius: 50%; display: flex; align-items: center; justify-content: center; color: white;">A</div>
                    </div>
                    <div class="avatar-option selected" data-avatar="star.jpg">
                        <img src="/static/star.jpg" alt="星星头像">
                    </div>
                </div>
            </div>
            <div class="form-group">
                <button type="button" class="submit-btn" onclick="register()">立即注册</button>
            </div>
            <div class="switch-form">
                已有账号？<a onclick="showLoginForm()">立即登录</a>
            </div>
            <div id="registerError" class="error-message"></div>
        </div>

        <div id="loginForm">
            <div style="display: flex; justify-content: space-between; align-items: center;">
                <h2>可用聊天室</h2>
                <button onclick="logout()" style="padding: 8px 15px; background: #dc3545; color: white; border: none; border-radius: 4px; cursor: pointer;">登出</button>
            </div>
            <div class="room-list" id="roomList">
                <!-- 房间列表将通过JavaScript动态添加 -->
            </div>
        </div>

        <div id="chatRoom">
            <div class="chat-container">
                <div class="chat-main">
                    <div class="chat-header">
                        <h2><span id="roomName"></span></h2>
                        <input type="submit" id="leaveButton" value="退出群聊" onclick="leave()">
                    </div>
                    <div id="messages"></div>
                    <div id="messageForm">
                        <input type="text" id="messageInput" placeholder="请输入消息">
                        <input type="submit" id="sendButton" value="发送" onclick="sendMessage()">
                    </div>
                </div>
                <div class="chat-sidebar">
                    <div class="online-users">
                        <div class="online-users-title">群成员 (<span id="onlineCount">0</span>)</div>
                        <div class="user-list" id="onlineUsersList">
                            <!-- 在线用户列表将通过JavaScript动态添加 -->
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/4.0.1/socket.io.js"></script>
    <script>
        const socket = io();
        let currentUsername = '';
        let currentRoom = '';
        let currentUserGender = '';
        let selectedAvatar = '';  // 存储选中的头像
        
        // 存储用户数据的对象
        const users = {
            'admin': '123456'
        };

        document.addEventListener('DOMContentLoaded', function() {
            // 检查本地存储中的登录信息
            const savedUser = localStorage.getItem('chatUser');
            if (savedUser) {
                const userData = JSON.parse(savedUser);
                // 自动登录
                autoLogin(userData);
            }

            // 添加头像选择的事件监听
            document.querySelectorAll('.avatar-option').forEach(option => {
                option.addEventListener('click', function() {
                    // 移除其他选项的选中状态
                    document.querySelectorAll('.avatar-option').forEach(opt => {
                        opt.classList.remove('selected');
                    });
                    // 添加当前选项的选中状态
                    this.classList.add('selected');
                    // 保存选中的头像
                    selectedAvatar = this.dataset.avatar;
                });
            });
        });

        async function autoLogin(userData) {
            try {
                const response = await fetch('/api/login', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({
                        username: userData.username,
                        password: userData.password
                    })
                });
                
                const data = await response.json();
                
                if (data.success) {
                    currentUsername = data.username;
                    currentUserGender = data.gender;
                    if (data.is_admin) {
                        window.location.href = '/admin?token=123456';
                    } else {
                        document.getElementById('authForm').style.display = 'none';
                        document.getElementById('loginForm').style.display = 'block';
                        document.body.classList.add('logged-in');  // 添加登录状态的类
                        updateRoomList(data.rooms);
                    }
                    document.getElementById('loginError').textContent = '';
                } else {
                    // 如果自动登录失败，清除本地存储
                    localStorage.removeItem('chatUser');
                    showLoginForm();
                }
            } catch (error) {
                console.error('Auto login error:', error);
                localStorage.removeItem('chatUser');
                showLoginForm();
            }
        }

        function showLoginForm() {
            document.getElementById('authForm').style.display = 'block';
            document.getElementById('registerForm').style.display = 'none';
            document.getElementById('loginError').textContent = '';
        }

        function showRegisterForm() {
            document.getElementById('authForm').style.display = 'none';
            document.getElementById('registerForm').style.display = 'block';
            document.getElementById('registerError').textContent = '';
        }

        async function login() {
            const username = document.getElementById('loginUsername').value;
            const password = document.getElementById('loginPassword').value;
            
            if (!username || !password) {
                document.getElementById('loginError').textContent = '请填写用户名和密码';
                return;
            }

            try {
                const response = await fetch('/api/login', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({ username, password })
                });
                
                const data = await response.json();
                
                if (data.success) {
                    localStorage.setItem('chatUser', JSON.stringify({
                        username: username,
                        password: password,
                        avatar: data.avatar
                    }));
                    
                    currentUsername = data.username;
                    if (data.is_admin) {
                        window.location.href = '/admin?token=123456';
                    } else {
                        document.getElementById('authForm').style.display = 'none';
                        document.getElementById('loginForm').style.display = 'block';
                        document.body.classList.add('logged-in');  // 添加登录状态的类
                        updateRoomList(data.rooms);
                    }
                    document.getElementById('loginError').textContent = '';
                } else {
                    document.getElementById('loginError').textContent = data.message;
                }
            } catch (error) {
                document.getElementById('loginError').textContent = '登录失败，请稍后重试';
                console.error('Login error:', error);
            }
        }

        async function register() {
            const username = document.getElementById('registerUsername').value;
            const password = document.getElementById('registerPassword').value;
            const confirmPassword = document.getElementById('confirmPassword').value;
            
            if (!username || !password || !confirmPassword) {
                document.getElementById('registerError').textContent = '请填写所有必填字段';
                return;
            }

            if (!selectedAvatar) {
                document.getElementById('registerError').textContent = '请选择头像';
                return;
            }

            if (password !== confirmPassword) {
                document.getElementById('registerError').textContent = '两次输入的密码不一致';
                return;
            }

            try {
                const response = await fetch('/api/register', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({ 
                        username, 
                        password,
                        avatar: selectedAvatar
                    })
                });
                
                const data = await response.json();
                
                if (data.success) {
                    showLoginForm();
                    document.getElementById('loginUsername').value = username;
                    document.getElementById('loginPassword').value = password;
                } else {
                    document.getElementById('registerError').textContent = data.message;
                }
            } catch (error) {
                document.getElementById('registerError').textContent = '注册失败，请稍后重试';
                console.error('Register error:', error);
            }
        }

        function join() {
            const room = document.getElementById('room').value;
            
            if (!room) {
                alert('请输入房间号');
                return;
            }

            currentRoom = room;
            socket.emit('join', {
                username: currentUsername,
                room: currentRoom
            });

            document.getElementById('loginForm').style.display = 'none';
            document.getElementById('chatRoom').style.display = 'block';
            document.getElementById('roomName').textContent = currentRoom;
        }

        function leave() {
            socket.emit('leave', {
                username: currentUsername,
                room: currentRoom
            });

            // 是否要清除登录信息由用户选择
            if (confirm('是否清除登录信息？下次需要重新登录')) {
                localStorage.removeItem('chatUser');
                document.getElementById('authForm').style.display = 'block';
            } else {
                document.getElementById('loginForm').style.display = 'block';
            }
            
            document.getElementById('chatRoom').style.display = 'none';
            document.getElementById('messages').innerHTML = '';
            currentRoom = '';
        }

        function sendMessage() {
            const messageInput = document.getElementById('messageInput');
            const message = messageInput.value;
            
            if (message.trim()) {
                socket.emit('message', {
                    username: currentUsername,
                    room: currentRoom,
                    message: message
                });
                messageInput.value = '';
            }
        }

        // 按回车发送消息
        document.getElementById('messageInput').addEventListener('keypress', function(e) {
            if (e.key === 'Enter') {
                sendMessage();
            }
        });

        socket.on('message', function(data) {
            // 确保消息属于当前房间
            if (currentRoom !== data.room) {
                return;
            }

            const messagesDiv = document.getElementById('messages');
            const messageContainer = document.createElement('div');
            messageContainer.className = 'message-container';
            
            // 如果是系统消息
            if (data.username === 'System') {
                const messageElement = document.createElement('div');
                messageElement.className = 'message system-message';
                messageElement.textContent = data.message;
                messageContainer.appendChild(messageElement);
                messagesDiv.appendChild(messageContainer);
                
                // 确保系统消息会淡出
                setTimeout(() => {
                    messageElement.classList.add('fade-out');
                    // 等待淡出动画完成后移除元素
                    setTimeout(() => {
                        if (messageContainer && messageContainer.parentNode) {
                            messageContainer.remove();
                        }
                    }, 500);
                }, 5000);
            } else {
                // 设置消息容器的方向
                if (data.username === currentUsername) {
                    messageContainer.className += ' right';
                }

                // 创建头像
                const avatarElement = document.createElement('div');
                avatarElement.className = 'message-avatar';

                // 根据用户的头像设置显示
                if (data.avatar === 'tiger') {
                    avatarElement.className += ' tiger';
                    avatarElement.innerHTML = '🐯';
                } else if (data.avatar === 'fish.png') {
                    avatarElement.style.backgroundImage = 'url("/static/fish.png")';
                } else if (data.avatar === 'star.jpg') {
                    avatarElement.style.backgroundImage = 'url("/static/star.jpg")';
                } else {
                    // 默认头像显示用户名首字母
                    avatarElement.textContent = data.username.charAt(0).toUpperCase();
                }

                // 创建消息内容包装器
                const contentWrapper = document.createElement('div');
                contentWrapper.className = 'message-content-wrapper';

                // 添加发送者名称
                const senderElement = document.createElement('div');
                senderElement.className = 'message-sender' + (data.username === currentUsername ? ' message-sender-right' : '');
                senderElement.textContent = data.username;
                contentWrapper.appendChild(senderElement);

                // 添加消息内容
                const messageElement = document.createElement('div');
                messageElement.className = 'message ' + (data.username === currentUsername ? 'message-right' : 'message-left');
                messageElement.textContent = data.message;
                contentWrapper.appendChild(messageElement);

                // 将头像和内容添加到容器
                messageContainer.appendChild(avatarElement);
                messageContainer.appendChild(contentWrapper);
                messagesDiv.appendChild(messageContainer);
            }
            
            messagesDiv.scrollTop = messagesDiv.scrollHeight;
        });

        socket.on('user_joined', function(data) {
            console.log('User joined:', data.username);
            if (data.users) {
                updateOnlineUsers(data.users);
            }
        });

        socket.on('user_left', function(data) {
            console.log('User left:', data.username);
            if (data.users) {
                updateOnlineUsers(data.users);
            }
        });

        socket.on('kicked', function(data) {
            alert(data.message);
            // 只显示登录表单，不清除登录信息
            document.getElementById('loginForm').style.display = 'block';
            document.getElementById('chatRoom').style.display = 'none';
            document.getElementById('messages').innerHTML = '';
            currentRoom = '';
        });

        function updateRoomList(rooms) {
            const roomList = document.getElementById('roomList');
            if (!roomList) return;
            
            roomList.innerHTML = '';
            
            Object.entries(rooms).forEach(([roomId, room]) => {
                const roomCard = document.createElement('div');
                roomCard.className = 'room-card';
                
                // 使用箭头函数来保持正确的this绑定
                roomCard.addEventListener('click', () => {
                    joinRoom(roomId, room.name);
                });
                
                roomCard.innerHTML = `
                    <div class="room-name">${room.name}</div>
                    <div class="room-info">创建者: ${room.created_by}</div>
                    <div class="room-info">创建时间: ${room.created_at}</div>
                    <div class="room-description">${room.description || '暂无描述'}</div>
                `;
                
                roomList.appendChild(roomCard);
            });
        }

        function joinRoom(roomId, roomName) {
            // 如果已经在房间中，先离开
            if (currentRoom) {
                socket.emit('leave', {
                    username: currentUsername,
                    room: currentRoom
                });
            }
            
            currentRoom = roomId;
            
            // 先显示聊天室界面
            const loginForm = document.getElementById('loginForm');
            const chatRoom = document.getElementById('chatRoom');
            const roomNameElement = document.getElementById('roomName');
            const messagesDiv = document.getElementById('messages');
            
            if (loginForm) loginForm.style.display = 'none';
            if (chatRoom) chatRoom.style.display = 'block';
            if (roomNameElement) roomNameElement.textContent = roomName;
            if (messagesDiv) messagesDiv.innerHTML = '';
            
            // 发送加入房间事件
            socket.emit('join', {
                username: currentUsername,
                room: currentRoom
            });
        }

        // 监听房间列表更新
        socket.on('rooms_update', function(rooms) {
            if (document.getElementById('loginForm').style.display === 'block') {
                updateRoomList(rooms);
            }
        });

        // 添加登出函数
        function logout() {
            document.body.classList.remove('logged-in');  // 移除登录状态的类
            localStorage.removeItem('chatUser');
            document.getElementById('loginForm').style.display = 'none';
            document.getElementById('authForm').style.display = 'block';
        }

        function updateOnlineUsers(users) {
            if (!users) return;
            
            const usersList = document.getElementById('onlineUsersList');
            const onlineCount = document.getElementById('onlineCount');
            
            if (!usersList || !onlineCount) return;
            
            usersList.innerHTML = '';
            const userArray = Object.values(users);
            onlineCount.textContent = userArray.length;
            
            userArray.forEach(userData => {
                if (!userData || !userData.username) return;
                
                const userItem = document.createElement('div');
                userItem.className = 'user-item';
                
                const avatar = document.createElement('div');
                avatar.className = 'user-item-avatar';
                
                try {
                    // 根据用户的头像设置显示
                    if (userData.avatar === 'tiger') {
                        avatar.className += ' tiger';
                        avatar.innerHTML = '🐯';
                    } else if (userData.avatar === 'fish.png') {
                        avatar.style.backgroundImage = 'url("/static/fish.png")';
                    } else if (userData.avatar === 'star.jpg') {
                        avatar.style.backgroundImage = 'url("/static/star.jpg")';
                    } else {
                        // 默认头像显示用户名首字母
                        avatar.textContent = userData.username.charAt(0).toUpperCase();
                    }
                    
                    const name = document.createElement('div');
                    name.className = 'user-item-name';
                    name.textContent = userData.username;
                    
                    userItem.appendChild(avatar);
                    userItem.appendChild(name);
                    usersList.appendChild(userItem);
                } catch (error) {
                    console.error('Error creating user item:', error);
                }
            });
        }

        // 心形流星雨
        function createHeart() {
            if (document.body.classList.contains('logged-in')) return;  // 登录后不创建动画
            
            const heart = document.createElement('div');
            heart.className = 'heart';
            
            heart.style.left = Math.random() * window.innerWidth + 'px';
            
            const size = Math.random() * 15 + 10;
            heart.style.width = size + 'px';
            heart.style.height = size + 'px';
            
            const duration = Math.random() * 2 + 2;
            heart.style.animationDuration = duration + 's';
            
            const colors = [
                '#ff69b4', // 热粉红
                '#ffb6c1', // 浅粉红
                '#ffc0cb', // 粉红
                '#ff1493', // 深粉红
                '#ff82ab'  // 亮粉红
            ];
            const color = colors[Math.floor(Math.random() * colors.length)];
            heart.style.background = color;
            
            document.body.appendChild(heart);
            
            setTimeout(() => {
                heart.remove();
            }, duration * 1000);
        }

        // 创建烟花
        function createFirework() {
            if (document.body.classList.contains('logged-in')) return;  // 登录后不创建动画
            
            const firework = document.createElement('div');
            firework.className = 'firework';
            
            const x = Math.random() * window.innerWidth;
            const y = Math.random() * (window.innerHeight * 0.6);
            firework.style.left = x + 'px';
            firework.style.top = y + 'px';

            const colors = [
                '#FF3232', // 鲜红色
                '#FF4500', // 红橙色
                '#FFD700', // 金色
                '#FFFFFF', // 纯白色
                '#FFA500', // 橙色
                '#FF69B4'  // 粉红色
            ];
            const color = colors[Math.floor(Math.random() * colors.length)];
            firework.style.backgroundColor = color;

            document.body.appendChild(firework);

            // 创建烟花粒子
            for (let i = 0; i < 40; i++) {
                const particle = document.createElement('div');
                particle.className = 'particle';
                particle.style.left = x + 'px';
                particle.style.top = y + 'px';
                particle.style.backgroundColor = color;

                const angle = (i / 40) * Math.PI * 2;
                const velocity = 150 + Math.random() * 100;
                particle.style.setProperty('--tx', Math.cos(angle) * velocity + 'px');
                particle.style.setProperty('--ty', Math.sin(angle) * velocity + 'px');

                document.body.appendChild(particle);

                setTimeout(() => {
                    particle.remove();
                }, 1200);
            }

            setTimeout(() => {
                firework.remove();
            }, 1200);
        }

        // 定时创建效果
        setInterval(createHeart, 150);    // 心形
        setInterval(createFirework, 1000); // 烟花
    </script>
</body>
</html> 